package com.example.auth.config;

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/** @author yang 自定义web安全配置类 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  /**
   * 认证管理
   *
   * @return 认证管理对象
   * @throws Exception 认证异常信息
   */
  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }

  /**
   * http安全配置 允许匿名访问所有接口 主要是 oauth 接口
   *
   * @param http http安全对象
   * @throws Exception http安全异常信息
   */
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    // http.formLogin()
    //         .and().authorizeRequests()
    //         .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
    //         .antMatchers("/rsa/publicKey").permitAll()
    //         .anyRequest().authenticated()
    //         .and().httpBasic()
    //         .and().cors()
    //         .and().csrf().disable();
    http.authorizeRequests()
        .requestMatchers(EndpointRequest.toAnyEndpoint())
        .permitAll()
        .antMatchers("/rsa/publicKey")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .httpBasic();
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring()
        .antMatchers(
            "/error",
            "/static/**",
            "/v2/api-docs/**",
            "/swagger-resources/**",
            "/webjars/**",
            "/rsa/publicKey",
            "/favicon.ico");
  }
}
